package code14JDBC;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 黄衡熙
 * @version 1.0
 */
public class Test06_保存返回主键 {
    public static void main(String[] args) {
        User user = new User("小李", "66666", "13532106687", "广东-东莞");
        System.out.println("保存前:" + user);
        Integer id = insertReturnPrimaryKey(user);
        System.out.println("返回的主键值:" + id);
        user.setId(id);
        System.out.println("保存后:" + user);
    }

    public static Integer insertReturnPrimaryKey(User user) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Integer id = null;//定义一个id
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" insert into t_user (username,password,phone,address) ")
                    .append(" values(?,?,?,?) ")
                    .toString();
            ps = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);//此处多了一个返回主键
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getPhone());
            ps.setString(4, user.getAddress());
            ps.executeUpdate();//获取状态
            rs = ps.getGeneratedKeys();//执行操作
            while (rs.next()) {
                id = rs.getInt(1);
            }
            return id;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBCUtil.close(conn, ps, rs);
        }
    }
}
